//
//  ICChatViewController+NotificationCenter.m
//  ICome
//
//  Created by zhangrongwu on 2017/1/5.
//  Copyright © 2017年 iCom. All rights reserved.
//

#import "ICChatViewController+NotificationCenter.h"
#import "ICSendRedPacketModel.h"

@implementation ICChatViewController (NotificationCenter)

- (void)initNotificationCenter
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messageDidReceivedUpdate:) name:NotificationReceiveMessageUpdate object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newGroupFirstGroup:) name:NotificationFirstMessage object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushMessageDidReceived) name:NotificationPushDidReceived object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messageDidBack:) name:NotificationBackMsgNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userHeaderImgChanged) name:NotificationUserHeadImgChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kickUserAction:) name:NotificationKickUserNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendRedPacket:) name:NotificationSendRedPacketNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareViewExited) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stayInApp) name:ICShareStayInAppNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backOtherApp) name:ICShareBackOtherAppNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForegroundRefresh:) name:NotificationEnterForegroundChatRefresh object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMessageStateRefresh:) name:NotificationUpdateMessageStateRefresh object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTopMessageRefresh:) name:NotificationGroupTopMessage object:nil];
    
}

#pragma mark - Received message
- (void)messageDidReceivedUpdate:(NSNotification *)notifi {
    NSDictionary *dic = notifi.object;
    ICMessageFrame *messageF = (ICMessageFrame *)[dic objectForKey:@"ICMessageFrame"];
    if ([messageF.model.message.to isEqualToString:self.group.gId]) {
        [self addObject:messageF isSender:NO];
        [self setupNav];
        self.chatBoxVC.view.hidden  = NO;
    }
}

// 本通知只更新UI 数据不处理
- (void)updateMessageStateRefresh:(NSNotification *)notifi {
    NSString *identify = notifi.object[@"identify"];
    
    [self.dataSource enumerateObjectsUsingBlock:^(ICMessageFrame *messageF, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([identify isEqualToString:messageF.model.message.messageId]||[identify isEqualToString:messageF.model.message.localMsgId]) { // 同一条消息
            messageF.model.message.deliveryState = [notifi.object[@"deliveryState"] intValue];
            [self.tableView reloadData];
            *stop = YES;
        }
    }];
}

- (void)newGroupFirstGroup:(NSNotification *)notify
{
    NSDictionary *dic = notify.userInfo;
    NSString *gId     = [dic objectForKey:@"gId"];
    if ([self.group.gId isEqualToString:gId]) {
        WEAKSELF
        [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:self.group.gId firstMessage:nil finish:^(NSArray *array, NSError *error) {
            if (array.count>0) {
                [weakSelf.dataSource removeAllObjects];
                [weakSelf.dataSource addObjectsFromArray:array];
                [weakSelf.tableView reloadData];
            } else {
                weakSelf.dataSource = nil;
                [weakSelf.tableView reloadData];
            }
        }];
        [ICMessageHelper updateGroupReadWithGroupId:self.group.gId];
        
        [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:self.group.gId count:0]; // 清除未读数
    }
}

- (void)pushMessageDidReceived
{
    [self refreshData];
}

- (void)refreshData
{
    WEAKSELF
    [ICMessageDatabase selectMessageWithCount:LoadMessageCount group:self.group.gId firstMessage:nil finish:^(NSArray *array, NSError *error) {
        if (array.count>0) {
            [weakSelf.dataSource removeAllObjects];
            [weakSelf.dataSource addObjectsFromArray:array];
            [weakSelf.tableView reloadData];
        }
    }];
}

- (void)messageDidBack:(NSNotification *)notify
{
    NSDictionary *dic = notify.userInfo;
    NSString *gId     = [dic objectForKey:@"gId"];
    NSString *msgId   = [dic objectForKey:@"msgId"];
    if (![gId isEqualToString:self.group.gId]) return;
    
    ICMessageFrame *messageF;
    for (ICMessageFrame *msgF in self.dataSource) {
        NSString *messsageId = [NSString stringWithFormat:@"%@",msgF.model.message.messageId];
        if ([messsageId isEqualToString:msgId]) {
            messageF = msgF;
            break;
        }
    }
    if (messageF == nil) return;
    NSInteger index = [self.dataSource indexOfObject:messageF];
    [self.dataSource removeObject:messageF];
    [self.tableView beginUpdates];
    [self.tableView deleteRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
    
    ICMessageFrame *msgF = [ICMessageDatabase getMessage:gId msgId:msgId];
    if (msgF.model == nil) return;
    [self.dataSource insertObject:msgF atIndex:index];
    [self.tableView reloadData];
}

// 解散或被踢
- (void)kickUserAction:(NSNotification *)notifi
{
    NSDictionary *dic = notifi.object;
    ICMessageFrame *messageF = (ICMessageFrame *)[dic objectForKey:@"ICMessageFrame"];
    if ([messageF.model.message.to isEqualToString:self.group.gId]) {
        [self invalidState];
        [self refreshData];
    }
}

- (void)invalidState
{
    [self.navigationItem.rightBarButtonItem setCustomView:[[UIView alloc] init]];
    self.chatBoxVC.view.hidden  = YES;
}

// 发送红包
- (void)sendRedPacket:(NSNotification *)notification {
    ICSendRedPacketModel *model = notification.object;
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeRedPacket
                                                           content:model.message
                                                              path:nil
                                                              from:[ICUser currentUser].eId
                                                                to:self.group.gId
                                                               lnk:model.message
                                                           fileKey:model.redId
                                                          isSender:YES
                                          receivedSenderByYourself:NO];
    messageF.model.message.deliveryState = ICMessageDeliveryState_Delivered;

    ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                     Message:TypeRedPacket
                                                     content:model.message
                                                     fileKey:model.redId
                                                        from:[ICUser currentUser].eId
                                                          to:self.group.gId
                                                         lnk:model.message
                                                      status:nil];
    message.messageId = model.snId;
    [self saveRedPacket:messageF Message:message];

    // 菊花转起来
    [self addObject:messageF isSender:YES];
}

// 进入前台刷新聊天
- (void)enterForegroundRefresh:(NSNotification *)notification {
    [self.dataSource removeAllObjects];
    [self loadDataSource];
}

- (void)userHeaderImgChanged
{
    [self.tableView reloadData];
}

- (void)shareViewExited
{
    if (_shareBgView) {
        _shareBgView = nil;
        self.shareContent = nil;
    }
}

- (void)stayInApp
{
    if (_shareBgView) {
        self.shareContent = nil;
    }
}

- (void)backOtherApp
{
    if (_shareBgView) {
        [ICReceiveShareObject callBackAppType:ICCallBackShare callBackScheme:self.shareContent.shareObject.message.urlSchemes ErrCode:IComSuccess errorStr:@"分享成功"];
        [self.navigationController popViewControllerAnimated:YES];
        self.shareContent = nil;
    }
}

- (void)updateTopMessageRefresh:(NSNotification *)notifi {
    [self showTopMessage];
}

@end
